package com.qindian.coupontest;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qindian.ExchangedCouponsAdapter;
import com.qindian.model.ExchangedCouponModel;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ExchangedCouponListActivity extends BaseActivity implements OnRefreshLoadmoreListener, BaseQuickAdapter.OnItemClickListener {

    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerCoupons;
    private ExchangedCouponsAdapter mAdapter;
    private boolean mIsRefresh = true;
    private int mCurrentPage = 1;
    private String mobile = "18852996181";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exchanged_coupon_list);
        mRefreshLayout = findViewById(R.id.layout_refresh);
        mRecyclerCoupons = findViewById(R.id.recycler_coupons);

        mRecyclerCoupons.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ExchangedCouponsAdapter(R.layout.item_exchanged_coupon);
        mAdapter.bindToRecyclerView(mRecyclerCoupons);
        mAdapter.setEmptyView(R.layout.empty_exchanged_coupon);
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mAdapter.setOnItemClickListener(this);

        getExchangedCouponList(mobile, 1);
    }

    private void getExchangedCouponList(final String mobile, int page) {

        if (mAdapter.getData().size() > 0) {
            showLoadingDialog();
        }
        Map<String, Object> map = new HashMap<>();
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        map.put("agent_id", Const.AGENT_ID);
        map.put("mobile", mobile);
        map.put("time", time);
        map.put("page", page);

        String prefix = "agent_id=" + Const.AGENT_ID + "&mobile=" + mobile + "&page=" + page;
        map.put("token", MD5Util.getMD5(prefix + time + Const.KEY));
        RetrofitHelper.createService().getExchangedCouponList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ExchangedCouponModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ExchangedCouponModel model) {
                        List<ExchangedCouponModel.DataBean.ListBean> list =
                                model.getData().getList() == null ? new ArrayList<ExchangedCouponModel.DataBean.ListBean>() : model.getData().getList();
                        if (mIsRefresh) {
                            mCurrentPage = 1;
                            mAdapter.setNewData(list);
                            if (model.getData().getTotal()
                                    > mAdapter.getData().size()) {
                                mRefreshLayout.setLoadmoreFinished(false);
                            } else {
                                mRefreshLayout.setLoadmoreFinished(true);
                            }
                        } else {
                            mAdapter.addData(list);
                            if (model.getData().getTotal()
                                    > mAdapter.getData().size()) {
                                mCurrentPage++;
                                mRefreshLayout.setLoadmoreFinished(false);
                            } else {
                                mRefreshLayout.setLoadmoreFinished(true);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        stopRefreshLoad();
                        showToast(e.toString());
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                        stopRefreshLoad();
                    }
                });

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mIsRefresh = false;
        getExchangedCouponList(mobile, mCurrentPage + 1);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mIsRefresh = true;
        getExchangedCouponList(mobile, 1);
    }

    private void stopRefreshLoad() {
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadmore();

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        String url = mAdapter.getData().get(position).getPlathform_url();
        Log.e("tag", "onItemClick: "+url);
        switch (mAdapter.getData().get(position).getIsjd()) {
            case 1:
                if (checkPackage("com.jingdong.app.mall")) {
                    String id=url.substring(url.lastIndexOf("/")+1,url.lastIndexOf(".html"));
                    Log.e("tag", "onItemClick: "+id);
                    String uri = "openapp.jdmobile://virtual?params=" +
                                "{\"sourceValue\":\"0_productDetail_97\"," +
                                "\"des\":\"productDetail\"," +
                                "\"skuId\":\"" + id + "\"," +
                                "\"category\":\"jump\"," +
                                "\"sourceType\":\"homefloor\"}";
                    Intent jdIntent=new Intent();
                    jdIntent.setData(Uri.parse(uri));
                    startActivity(jdIntent);
                }else {
                    Intent webIntent = new Intent(ExchangedCouponListActivity.this, WebActivity.class);
                    webIntent.putExtra("title","商品详情");
                    webIntent.putExtra("url", url);
                    startActivity(webIntent);
                }

                break;
            case 0:
                if (checkPackage("com.taobao.taobao")) {
                    Intent tbIntent = new Intent();
                    tbIntent.setAction(Intent.ACTION_VIEW);
                    tbIntent.setData(Uri.parse(url));
                    tbIntent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
                    startActivity(tbIntent);
                }else {
                    Intent webIntent = new Intent(ExchangedCouponListActivity.this, WebActivity.class);
                    webIntent.putExtra("title","商品详情");
                    webIntent.putExtra("url", url);
                    startActivity(webIntent);
                }

                break;
        }
    }

    private boolean checkPackage(String packageName) {
        PackageManager manager = getPackageManager();
        List<PackageInfo> packages = manager.getInstalledPackages(0);
        for (PackageInfo info : packages) {
            if (info.packageName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }
}
